import tinymce from 'tinymce';
import markdownit from 'markdown-it';
import { seq, replaceAsync } from './replace';
import { uploadImage } from './upload';
import i18n from '@/settings/i18n';

const reImage = /!\[([^\]]*?)\]\(([^)]*?)\)/g;

const uploadImageAndReplaceUrl = async (content: string) => await replaceAsync(content, reImage, seq(async (_: string, p1: string, p2: string) => {
  const url = await uploadImage(p2);

  return `![${p1}](${url})`;
}));

tinymce.PluginManager.add('markdownit', (editor) => {
  const openDialog = () => editor.windowManager.open({
    title: i18n.global.t('settings.component.richEditor.plugins.markdownIt.title'),
    size: 'large',
    body: {
      type: 'panel',
      items: [{
        type: 'textarea',
        name: 'code',
      }],
    },
    buttons: [
      {
        type: 'cancel',
        name: 'cancel',
        text: 'Cancel',
      },
      {
        type: 'submit',
        name: 'save',
        text: 'Save',
        primary: true,
      },
    ],
    async onSubmit(api) {
      let content = api.getData().code.trim();

      if (content) {
        api.block(i18n.global.t('settings.component.richEditor.loading'));

        content = await uploadImageAndReplaceUrl(content);

        const md = markdownit();

        editor.insertContent(md.render(content));
      }

      api.close();
    },
  });

  /* Add a button that opens a window */
  editor.ui.registry.addButton('markdownit', {
    text: 'MD',
    icon: 'sourcecode',
    tooltip: i18n.global.t('settings.component.richEditor.plugins.markdownIt.title'),
    onAction: () => {
      openDialog();
    },
  });

  /* Adds a menu item, which can then be included in any menu via the menu/menubar configuration */
  editor.ui.registry.addMenuItem('markdownit', {
    icon: 'sourcecode',
    text: i18n.global.t('settings.component.richEditor.plugins.markdownIt.title'),
    onAction: () => {
      openDialog();
    },
  });

  return {};
});
